use clap::{ArgMatches, Command};

use crate::environment::environment;
use crate::index::index;
use crate::util::util::installer::installer;

pub(super) const NAME: &'static str = "ini";

pub(super) fn new() -> Command {
    Command::new(NAME).about("从当前项目配置初始化环境")
}

pub(super) fn action(_: &ArgMatches) {
    install_tools(); // 安装工具
}

fn install_tools() {
    let software = environment::project().get_software();
    if 0 == software.len() {
        return;
    }

    for (name, version_name) in software.iter() {
        let software = index::index().get(name);
        if software.is_none() {
            println!("无效的自定义环境配置，未找到工具[{}]信息，请检查项目配置是否正确", name);

            return;
        }

        let version = software.unwrap().get_version(version_name);
        if version.is_none() {
            println!("无效的自定义环境配置，未找到工具[{}]的[{}]版本信息，请检查项目配置是否正确", name, version_name);

            continue;
        }

        if environment::is_installed(name, version_name) {
            continue;
        }

        let result = installer::Installer::install(name, version.unwrap(), false);
        if result.is_err() {
            println!("安装工具[{}]的[{}]版本失败，失败原因: {}", name, version_name, result.unwrap_err());
        }
    }
}